package client;

import java.io.IOException;
import java.net.Socket;

import security.Channel;
import security.TCPChannel;
import security.TimestampUtil;

/**
 * Accepts a timestamp request and responds to it.
 * Only the first incoming message is processed.
 * 
 * @author Lukas
 *
 */
public class TimestampHandler extends Thread {
	private Channel channel;
	
	/**
	 * Constructor.
	 * @param socket The socket with the incoming !getTimestamp-request.
	 * @throws IOException
	 */
	public TimestampHandler(Socket socket) throws IOException {
		channel = new TCPChannel(socket);
	}
	
	@Override
	public void run() {
		try {
			String message = channel.receive();
			if (message.startsWith("!getTimestamp ")) {
				message = "!t" + message.substring(5) + ' ' + System.currentTimeMillis();
				String sig = TimestampUtil.getSignature(message, Client.username);
				channel.send(message + ' ' + sig);
			}
		} catch (IOException e) {
			System.out.println("an error occured during processing a timestamp request");
		} finally {
			try {
				channel.close();
			} catch (IOException e) {
				System.out.println("connection to timestamp requesting client could not be closed");
			}
		}
	}
}
